<template>
    <ui-main class="mt0 mr5 ml5 mb5">
        <train-title slot="header"></train-title>

        <template v-if="listData.length">
            <div class="f18 f-bold text-center" slot="header">第 {{pageNumber + 1}}/{{total}} 题</div>

            <xx class="mt5" ref="xx" :question="currQuestion"></xx>

            <div class="flex row-between col-center mt5" slot="footer">
                <van-button type="default" size="small" :disabled="prevDisabled" @click="prev">
                    <i class="fa fa-angle-left f16"></i>
                    上一题
                </van-button>

                <div class="ml20 mr20 flex-1" v-show="pageNumber === (listData.length - 1)">
                    <van-button type="primary" size="small" block @click="submit">提交</van-button>
                </div>

                <van-button type="default" size="small" :disabled="nextDisabled" @click="next">
                    下一题
                    <i class="fa fa-angle-right f16"></i>
                </van-button>
            </div>
        </template>
    </ui-main>
</template>

<script>
    import trainTitle from './train-title';
    import xx from './选项';
    import cy from '../mixins/cy';

    export default {
        components: {trainTitle, xx},
        mixins: [cy],
        data() {
            return {
                // 数据源
                // 题库
                listData: [],
                // 其他
                // 当前题目
                currQuestion: null,
                // 第几题
                pageNumber: 0,
                // 题目数量
                total: 5,
                // 是否禁用上一题：true-是；false-否
                prevDisabled: true,
                // 是否禁用下一题：true-是；false-否
                nextDisabled: true
            };
        },
        mounted() {
            this.$title('在线培训');

            this.$loading.open();

            this.$$questionRandomQuery(this.total).then(data => {
                data.content.forEach(item => {
                    for (let key in item) {
                        if (this.$startsWithStr(key, 'answer_') && !this.$endsWithStr(key, '_check')) {
                            item[`${key}_check`] = false;
                        }
                    }
                });
                this.listData = data.content;

                this.load();

                this.$loading.close();
            }).catch(e => {
                console.error(e);

                this.$loading.close();
            });
        },
        methods: {
            // 上一题
            prev() {
                if (this.pageNumber > 0) {
                    this.pageNumber--;
                }

                this.load();
            },
            // 下一题
            next() {
                if (this.pageNumber < (this.listData.length - 1)) {
                    this.pageNumber++;
                }

                this.load();
            },
            // 加载题目
            load() {
                if (this.listData.length) {
                    this.currQuestion = this.listData[this.pageNumber];

                    if ((this.pageNumber <= 0) || (this.listData.length === 1)) {
                        this.prevDisabled = true;
                    } else {
                        this.prevDisabled = false;
                    }

                    if (this.pageNumber >= (this.listData.length - 1)) {
                        this.nextDisabled = true;
                    } else {
                        this.nextDisabled = false;
                    }
                }
            },
            // 提交答卷
            submit() {
                if (!this.listData.length) {
                    this.$toast('尚未获取题库，禁止提交答卷');

                    return;
                }

                // 尚未作答的题目序号数组
                let unAnswerQuestionIndexs = [];

                // 校验全部题目
                for (let i = 0; i < this.listData.length; i++) {
                    let item = this.listData[i];

                    // 选择答案的个数
                    let checkAnswerCount = 0;

                    for (let key in item) {
                        // 已选择答案
                        if (this.$startsWithStr(key, 'answer_') && this.$endsWithStr(key, '_check') && item[key]) {
                            checkAnswerCount++
                        }
                    }

                    // 尚未作答
                    if (checkAnswerCount <= 0) {
                        unAnswerQuestionIndexs.push(i + 1);
                    }
                }

                // 错误提示
                let errMsg = '';
                if (unAnswerQuestionIndexs.length) {
                    errMsg = `第${this.$parseArrayToStr(unAnswerQuestionIndexs, ',')}题尚未作答，`;
                }

                errMsg += '确定提交答卷吗？';

                this.$dialog.confirm({
                    message: errMsg
                }).then(() => {
                    this.$loading.open();

                    // 整理答卷
                    let answerSheet = [];
                    this.listData.forEach(item => {
                        let ans = '';

                        for (let key in item) {
                            // 获得答案
                            if (this.$startsWithStr(key, 'answer_') &&
                                this.$endsWithStr(key, '_check') &&
                                item[key]) {
                                ans += key.substr(7, 1);
                            }
                        }

                        answerSheet.push({
                            customer_id: this.$user.customer_id,
                            person_id: this.$user.person_id,
                            questions_id: item.id,
                            ans: ans.toUpperCase(),
                            percent: '',
                            operator_id: this.$user.person_id,
                            operator_name: this.$user.person_name
                        });
                    });

                    this.$$correctAnswerSheet(this.$jsonToStr(answerSheet)).then(() => {
                        this.$loading.close();
                        this.$toast('提交答卷成功');

                        this.$router.replace({
                            path: '/pxjg'
                        });
                    }).catch(e => {
                        console.error(e);

                        this.$loading.close();
                        this.$toast('网络错误，提交答卷失败')
                    });
                }).catch(e => {
                    if (e) {
                        console.error(e);
                    } else {
                        console.error(new Error('已取消'));
                    }
                });
            }
        }
    }
</script>
